const {
	Controller
} = require("uni-cloud-router");
const {
	success,
	fail,
	verify_token,
	build_token,
	create_uuid,
	encrypt,
	decrypt,
	isFieldExist,
	whereObj,
	isHttpMethod,
	isAdmin,
	isSuperAdmin,
	isAuthorities,
	
} = require('mh-utils');
//静态配置
const createConfig = require('uni-config-center')
const { count } = require("console");
const envCfg = createConfig({
	pluginId: 'env'
}).config()

module.exports = class OrganizationController extends Controller {
	// [sys:org:list, sys:org:add, sys:org:update, sys:org:delete]
	
	/**
	 * 获取全部组织机构
	 */
	async list(){
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'GET')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:org:list')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
			}
			try{
				var where = '';
				if (!isSuperAdmin(ctx)) {
					where = whereObj({where,query:`tenantId=='${ctx.auth.tenantId}'`});
				}
				where = whereObj({where,query:`deleted != 1`});
				var sort = 'sortNumber';
				var order = 'asc';
				var result = await dbJQL.collection("mh-sys-organization, mh-sys-user")
					.foreignKey('mh-sys-organization.leaderId')
					.where(`${where}`)
					.orderBy(`${sort}`, `${order}`)
					.get()
				if(result.data){
					return success({
						code: 0,
						data: result.data
					})
				}
				return fail({
					code: 1,
				})
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 新增
	 * @example data
	 */
	async add() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'POST')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:org:add')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
			}
			try{
				delete ctx.data._id;
				var result = await dbJQL.collection("mh-sys-organization")
					.add({
						...ctx.data,
						"createUserId": ctx.auth.loginUserId,
						"tenantId": ctx.auth.tenantId,
					})
				if(result.id) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 修改
	 * @example data
	 */
	async update() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'PUT')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:org:update')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
				if(ctx.auth.loginUserId != ctx.data.createUserId) {
					return fail({
						code: 1,
						message: '不可操作非本人数据'
					})
				}
			}
			try{
				var organizationId = ctx.data._id;
				if(!organizationId) return fail({
					code: 1,
					message: '参数无效'
				})
				delete ctx.data._id; //_id带到查询数据库会报错
				delete ctx.data.tenantId;
				var result = await dbJQL.collection("mh-sys-organization")
					.doc(organizationId)
					.update({
						...ctx.data,
						updateTime: new Date().getTime()
					})
				if(result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 删除
	 * @example ?_id=111111&&createUserId=2222222
	 */
	async remove() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'DELETE')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:org:delete')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
				if(ctx.auth.loginUserId != ctx.query.createUserId) {
					return fail({
						code: 1,
						message: '不可操作非本人数据'
					})
				}
			}
			
			try{
				var organizationId = ctx.query._id;
				if(!organizationId) return fail({
					code: 1,
					message: '参数无效'
				})
				var existOrg = await dbJQL.collection("mh-sys-organization")
					.where(`parentId == '${organizationId}' && deleted == 0`)
					.count();
				if(existOrg.total >= 1){
					return fail({
						code: 1,
						message: '请先删除下级的组织机构'
					})
				}
				//删除组织机构
				var result = await dbJQL.collection("mh-sys-organization")
					.doc(organizationId)
					.update({
						deleted: 1,
						updateTime: new Date().getTime()
					})
				//对应user的organizationId也清空
				await dbJQL.collection("mh-sys-user")
					.where(`organizationId == '${organizationId}'`)
					.update({
						organizationId: null,
						updateTime: new Date().getTime()
					})
				if(result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 根据organizationId分页获取用户
	 * @example ?_id=111111
	 */
	async pageUserByOrg() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'GET')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:user:list')) {
					return fail({
						code: 1,
						message: '该用户没有查询用户权限'
					})
				}
			}
			try{
				var where = "";
				
				// 查询条件
				var orgId = ctx.data._id;
				var username = ctx.data.username;
				var nickname = ctx.data.nickname;
				var sort = ctx.data.sort || null;
				var order = ctx.data.order || 'asc';
				if (isFieldExist(username)) {
					//模糊查询
					where = whereObj({where,query:`${new RegExp(username,'i')}.test(username)`});
				}
				if (isFieldExist(nickname)) {
					//模糊查询
					where = whereObj({where,query:`${new RegExp(nickname,'i')}.test(nickname)`});
				}
				if(orgId=="-1" || !orgId) {
					where = whereObj({where,query:`(organizationId == null || organizationId == "")`});
				}else{
					where = whereObj({where,query:`organizationId == "${orgId}"`});
				}
				where = whereObj({where,query:`tenantId=="${ctx.auth.tenantId}"`});	
				where = whereObj({where,query:`deleted != 1`});
				// 分页
				var page = ctx.data.page || 1;
				var limit = ctx.data.limit || 500;
				var result = await dbJQL.collection("mh-sys-user")
					.where(`${where}`)
					.orderBy(`${sort}`, `${order}`)
					.skip((page*1 - 1) * limit)
					.limit(limit*1)
					.get({
						getCount: true
					})
				if(!result.data){
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
				return success({
					code: 0,
					data: {
						list: result.data,
						count: result.count,
					}
				})
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
};
